package com.hk.utils;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class ReflectUtil {

	public static Object setPropToBeanFromResultSet(Object resultType,ResultSet resultSet) {
		// 该方法 Retrieves the number, types
		// and properties of this ResultSet object's columns.
		try {
		ResultSetMetaData metaData = resultSet.getMetaData();
		Field[] fields = resultType.getClass().getDeclaredFields();
		int count = metaData.getColumnCount();
		for (int i = 0; i < count; i++) {
			String columnName = metaData.getColumnName(i+1);
					//.replace("_", "");
			for (int j = 0; j < fields.length; j++) {
				String field = fields[j].getName();
				if (field.equalsIgnoreCase(columnName)) {
					if (fields[j].getType().getSimpleName().equals("Integer") || fields[j].getType().getSimpleName().equals("int")) {
						setPropToBean( resultType, field, resultSet.getInt(i + 1));
					} else if (fields[j].getType().getSimpleName().equals("Float") || fields[j].getType().getSimpleName().equals("float")) {
						setPropToBean( resultType, field, resultSet.getFloat(i + 1));
					} else if (fields[j].getType().getSimpleName().equals("Double") || fields[j].getType().getSimpleName().equals("double")) {
						setPropToBean( resultType, field, resultSet.getDouble(i + 1));
					} else if (fields[j].getType().getSimpleName().equals("String")) {
						setPropToBean( resultType, field, resultSet.getString(i + 1));
					} else if (fields[j].getType().getSimpleName().equals("Boolean") || fields[j].getType().getSimpleName().equals("boolean")) {
						setPropToBean( resultType, field, resultSet.getBoolean(i + 1));
					} else if (fields[j].getType().getSimpleName().equals("Long") || fields[j].getType().getSimpleName().equals("long")) {
						setPropToBean( resultType, field, resultSet.getLong(i + 1));
					}
					break;
				}

			}
		}

	}catch(SQLException e)
	{
		e.printStackTrace();
	}
	return resultType;
}

	private static void setPropToBean(Object bean, String name, Object vaule) {
		Field field;
		try {
			field = bean.getClass().getDeclaredField(name);
			field.setAccessible(true);
			// 从field直接注入value
			field.set(bean, vaule);
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}
}
